﻿using EYangFrame.DataAccess.Global;
using EYangFramework.Business.SystemManager.Interfaces;
using EYangFramework.Common.Ninject;
using EYangFramework.Domain.Entitys.Entrys;
using EYangFramework.Domain.Entitys.ValueObjects;
using SMES.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace EYangFramework.SystemManager
{
    public partial class frm_UserManager : EYangFramework.CommonForm.frm_BasicForm
    {
        List<User> users;
        bool isAdd = false;
        public frm_UserManager()
        {
            InitializeComponent();
        }

        private void frm_UserManager_Load(object sender, EventArgs e)
        {
            SetTabVisible(tp_Detail, false);
            BindList();
            tv_List.ExpandAll();
        }

        private void BindList()
        {
            tv_List.Nodes.Clear();
            using (IBLLUser bLLUser = NinjectProvider.NinjectCore.GetService<IBLLUser>())
            {
                users = bLLUser.GetAllList();
                TreeNode root = new TreeNode();
                root.Text = "用户清单";
                root.Tag = null;
                tv_List.Nodes.Add(root);
                BindTree(users.Where(u => u.LEADER == null).ToList(), root);
            }
        }

        private void BindTree(List<User> currentUsers, TreeNode node)
        {
            foreach (User item in currentUsers)
            {
                TreeNode currentNode = new TreeNode();
                currentNode.Text = item.USERNAME;
                currentNode.Tag = item.ID.ToString();
                node.Nodes.Add(currentNode);
                List<User> childUsers = users.Where(u => u.LEADER?.ID == item.ID).ToList();
                if (childUsers.Count > 0)
                {
                    BindTree(childUsers, currentNode);
                }
            }
        }
        //绑定用户下拉框
        private void BindLeader()
        {
            comLeader.Items.Clear();
            foreach (var item in users)
            {
                comLeader.Items.Add(item.USERNAME);
            }
        }
        //绑定角色下拉框
        private void BindRole()
        {
            comRole.Items.Clear();
            using (IBLLUser bLLUser = NinjectProvider.NinjectCore.GetService<IBLLUser>())
            {
                List<string> roles = bLLUser.GetRoleNameList();
                roles.ForEach(r =>
                {
                    comRole.Items.Add(r);
                });
            }
        }
        //绑定用户信息
        private void BindUserInfo(User user)
        {
            txtUserName.Text = user?.USERNAME;
            txtEmail.Text = user?.EMAIL;
            txtPhone.Text = user?.PHONE;
            comGender.SelectedIndex = user?.GENDER != Gender.Male ? 1 : 0;
            comLeader.Text = user?.LEADER?.USERNAME;
            comRole.Text = user?.ROLE.ROLENAME;
            txtPassword.Text = "";
            txtConfirmPassword.Text = "";
        }
        //设置容器内部控件的显示
        private void ShowDetail(bool changePassword)
        {
            txtPassword.Visible = isAdd || changePassword;
            txtConfirmPassword.Visible = isAdd || changePassword;
            txtUserName.ReadOnly = !isAdd && changePassword;
            txtEmail.ReadOnly = !isAdd && changePassword;
            txtPhone.ReadOnly = !isAdd && changePassword;
            comGender.Enabled = !(!isAdd && changePassword);
            comRole.Enabled = !(!isAdd && changePassword);
            comLeader.Enabled = !(!isAdd && changePassword);
            label7.Visible = txtPassword.Visible;
            label8.Visible = txtConfirmPassword.Visible;
        }

        private void menu_View_Click(object sender, EventArgs e)
        {
            if (tv_List.SelectedNode == null || tv_List.SelectedNode.Tag == null)
            {
                MessageBox.Show("请选择需要查看的用户!");
                return;
            }
            tableLayoutPanel1.Enabled = false;
            isAdd = false;
            ShowDetail(false);
            BindRole();
            BindLeader();
            using (IBLLUser bLLUser = NinjectProvider.NinjectCore.GetService<IBLLUser>())
            {
                User current = bLLUser.GetBusinessByID(Guid.Parse(tv_List.SelectedNode.Tag.ToString()));
                BindUserInfo(current);
                groupUser.Tag = tv_List.SelectedNode.Tag.ToString();
                groupUser.Text = $"你正在查看{current.USERNAME}的信息!";
            }
            btnSave.Visible = false;
            SetTabVisible(tp_Detail, true);
        }

        private void menu_Add_Click(object sender, EventArgs e)
        {
            isAdd = true;
            ShowDetail(false);
            BindUserInfo(null);
            BindRole();
            BindLeader();
            groupUser.Tag = null;
            groupUser.Text = "你正在新增用户!";
            SetTabVisible(tp_Detail, true);
            tableLayoutPanel1.Enabled = true;
            btnSave.Visible = true;
        }

        private void menu_Edit_Click(object sender, EventArgs e)
        {
            if (tv_List.SelectedNode == null || tv_List.SelectedNode.Tag == null)
            {
                MessageBox.Show("请选择需要编辑的用户!");
                return;
            }
            isAdd = false;
            ShowDetail(false);
            tableLayoutPanel1.Enabled = true;
            using (IBLLUser bLLUser = NinjectProvider.NinjectCore.GetService<IBLLUser>())
            {
                User current = bLLUser.GetBusinessByID(Guid.Parse(tv_List.SelectedNode.Tag.ToString()));
                BindUserInfo(current);
                groupUser.Tag = tv_List.SelectedNode.Tag.ToString();
                groupUser.Text = $"你正在编辑{current.USERNAME}的信息!";
            }
            BindRole();
            BindLeader();
            SetTabVisible(tp_Detail, true);
            btnSave.Visible = true;
        }

        private void menu_ChangePassword_Click(object sender, EventArgs e)
        {
            if (tv_List.SelectedNode == null || tv_List.SelectedNode.Tag == null)
            {
                MessageBox.Show("请选择需要修改密码的用户!");
                return;
            }
            isAdd = false;
            ShowDetail(true);
            tableLayoutPanel1.Enabled = true;
            using (IBLLUser bLLUser = NinjectProvider.NinjectCore.GetService<IBLLUser>())
            {
                User current = bLLUser.GetBusinessByID(Guid.Parse(tv_List.SelectedNode.Tag.ToString()));
                BindUserInfo(current);
                groupUser.Tag = tv_List.SelectedNode.Tag.ToString();
                groupUser.Text = $"你正在修改{current.USERNAME}的密码!";
            }
            SetTabVisible(tp_Detail, true);
            btnSave.Visible = true;
        }

        private void menu_Delete_Click(object sender, EventArgs e)
        {
            if (tv_List.SelectedNode == null || tv_List.SelectedNode.Tag == null)
            {
                MessageBox.Show("请选择需要删除的用户!");
                return;
            }
            if (MessageBox.Show("你确定要删除选中的用户吗?删除后如需重新放出,请联系管理员!", "警告!", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
            {
                return;
            }
            using (IBLLUser bLLUser = NinjectProvider.NinjectCore.GetService<IBLLUser>())
            {
                User current = bLLUser.GetBusinessByID(Guid.Parse(tv_List.SelectedNode.Tag.ToString()));
                bool isSuccess = bLLUser.DeleteUser(current);
                if (isSuccess)
                {
                    MessageBox.Show("删除成功!");
                    BindList();
                }
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtUserName.Text))
            {
                MessageBox.Show("用户名不能为空!");
                return;
            }
            if (string.IsNullOrEmpty(txtEmail.Text))
            {
                MessageBox.Show("邮箱不能为空!");
                return;
            }
            if (string.IsNullOrEmpty(txtUserName.Text))
            {
                MessageBox.Show("电话不能为空!");
                return;
            }
            if (string.IsNullOrEmpty(comGender.Text))
            {
                MessageBox.Show("性别不能为空!");
                return;
            }
            if (string.IsNullOrEmpty(comRole.Text))
            {
                MessageBox.Show("所属角色不能为空!");
                return;
            }
            if (txtPassword.Visible && string.IsNullOrEmpty(txtPassword.Text))
            {
                MessageBox.Show("密码不能为空!");
                return;
            }
            if (txtPassword.Visible && txtPassword.Text != txtConfirmPassword.Text)
            {
                MessageBox.Show("两次输入密码不同,请重新输入!");
                return;
            }
            User user;
            bool isSuccess = false;
            if (isAdd)
            {
                user = new User();
                user.USERNAME = txtUserName.Text;
                user.EMAIL = txtEmail.Text;
                user.PHONE = txtPhone.Text;
                user.GENDER = comGender.Text == "男" ? Gender.Male : Gender.FaleMale;
                user.PASSWORD = CEncoder.encryptMD5(txtPassword.Text);
                user.CREATEUSER = GlobalInfo.CurrentUser.USERNAME;
                user.ISADMIN = false;
                user.ISDELETE = false;
                user.ISLOCKED = false;
                user.CHANGEPASSWORD = false;
                using (IBLLUser bLLUser = NinjectProvider.NinjectCore.GetService<IBLLUser>())
                {
                    if (bLLUser.GetUserByName(txtUserName.Text) != null)
                    {
                        MessageBox.Show("当前用户已存在,请重新输入!","提示!");
                        return;
                    }
                    user.ROLE = bLLUser.GetRoleByName(comRole.Text);
                    user.LEADER = string.IsNullOrEmpty(comLeader.Text) ? null : bLLUser.GetUserByName(comLeader.Text);
                    isSuccess = bLLUser.InsertUser(user);
                }
            }
            else
            {
                Guid id = Guid.Parse(groupUser.Tag.ToString());
                using (IBLLUser bLLUser = NinjectProvider.NinjectCore.GetService<IBLLUser>())
                {
                    user = bLLUser.GetBusinessByID(id);
                    if (user == null)
                    {
                        throw new Exception("未查询到指定用户,请联系管理员!");
                    }
                    if (txtPassword.Visible)
                    {
                        user.PASSWORD = CEncoder.encryptMD5(txtPassword.Text);
                    }
                    else
                    {
                        user.USERNAME = txtUserName.Text;
                        user.EMAIL = txtEmail.Text;
                        user.PHONE = txtPhone.Text;
                        user.GENDER = comGender.Text == "男" ? Gender.Male : Gender.FaleMale;
                        user.ROLE = bLLUser.GetRoleByName(comRole.Text);
                        user.LEADER = string.IsNullOrEmpty(comLeader.Text) ? null : bLLUser.GetUserByName(comLeader.Text);
                    }
                    isSuccess = bLLUser.UpdateUser(user);
                }
            }
            if (isSuccess)
            {
                MessageBox.Show("保存成功!");
                btnCancel_Click(null, null);
                BindList();
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (sender == null || MessageBox.Show("你确定要退出编辑模式吗?", "提醒!", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                SetTabVisible(tp_Detail, false);
            }
        }

        private void tv_List_DoubleClick(object sender, EventArgs e)
        {
            menu_View_Click(null, null);
        }
    }
}
